<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/7/31
 * Time: 2:53 PM
 */

namespace app\astrologer\controller\v4;

use app\aliyun\controller\AliyunFilterWord;
use app\astrologer\controller\AstrAuth;
use app\astrologer\controller\Upload;
use app\common\cachemodel\zlcr3\Zlcr3AstrModifyCheck;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAuthCode;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\cachemodel\ZlcrAstrInfo;
use app\common\cachemodel\ZlcrContentCheck;
use app\common\lib\Util;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Env;
use think\exception\DbException;
use think\Log;
use think\response\Json;

class User extends AstrAuth
{

    /**
     * 个人中心
     * @return Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function info()
    {
        $host = Env::get('host.photo');
        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($this->astrInfo['id'], ['balance']);
        $authStatus = $this->astrInfo['auth_status'];
        $passList = [
            0 => $authStatus['custom_report'],
            1 => $authStatus['question_answer_astr'],
            2 => $authStatus['question_answer_dice'],
            3 => $authStatus['question_answer_tarot'],
        ];
//        $checkStatus = \app\astrologer\controller\User::$statusInfo[$this->astrInfo['check_status']];
        if ($this->astrInfo['uid'])
        {
            $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $this->astrInfo['uid']]);
        }

        return show(config('code.success'), '', [
            'id' => $this->astrInfo['id'],
            'name' => $this->astrInfo['nickname'],
            'avatar' => $this->astrInfo['avatar'] ? $host . $this->astrInfo['avatar'] : '',
            'balance' => $accountInfo['balance'],
            'exam_status' => array_sum($passList) === 1 ? '还有考核未通过' : '全部通过',
            'is_profile_completed' => isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0,
            'pass_list' => $passList,
            'uen' => $userInfo['uen'] ?? ''
        ]);
    }

    /**
     * 主页
     * @return Json
     * @throws \Exception
     */
    public function homePage()
    {
        $res = (new ZlcrAstr())->homePage($this->astrInfo, 2);
        unset($res['status']);
        return show(config('code.success'), '', $res);
    }

    /**
     * 个人信息
     * @return Json
     */
    public function profileInfo()
    {
        $extend = $this->astrInfo['extend'];
        $checkInfo = (new Zlcr3AstrModifyCheck())->checkTypeInfo($this->astrInfo['id']);
        $isCompleteInformation = isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0;

        $resData = [
            [
                'title' => '头像',
                'placeholder' => '',
                'content' => !empty($checkInfo['avatar']) ? $checkInfo['avatar'] : $this->astrInfo['avatar'],
                'pic_list' => [],
                'status' => $isCompleteInformation === 1 ? (!empty($checkInfo['avatar']) ? 2 : 1) : 0,
            ], [
                'title' => '昵称',
                'placeholder' => '请输入昵称',
                'content' => !empty($checkInfo['nickname']) ? $checkInfo['nickname'] : $this->astrInfo['nickname'],
                'pic_list' => [],
                'status' => $isCompleteInformation === 1 ? (!empty($checkInfo['nickname']) ? 2 : 1) : 0,
            ], [
                'title' => '咨询师简介',
                'placeholder' => '详细介绍一下自己吧～',
                'content' => !empty($checkInfo['content']) ? $checkInfo['content'] : ($extend['qualification']['content'] ?? ''),
                'pic_list' => !empty($checkInfo['pic_list']) ? $checkInfo['pic_list'] : (!empty($extend['qualification']['pic_list']) ? $extend['qualification']['pic_list'] : []),
                'status' => $isCompleteInformation === 1 ? (!empty($checkInfo['content']) ? 2 : 1) : 0,
            ], [
                'title' => '营业介绍',
                'placeholder' => '用一句话吸引用户看到',
                'content' => !empty($checkInfo['work_intro']) ? $checkInfo['work_intro'] : ($extend['work_intro'] ?? ''),
                'pic_list' => [],
                'status' => $isCompleteInformation === 1 ? (!empty($checkInfo['work_intro']) ? 2 : 1) : 0,
            ], [
                'title' => '服务时间',
                'placeholder' => '简单说一下你的服务时间',
                'content' => !empty($checkInfo['service_time']) ? $checkInfo['service_time'] : ($extend['service_time'] ?? ''),
                'pic_list' => [],
                'status' => $isCompleteInformation === 1 ? (!empty($checkInfo['service_time']) ? 2 : 1) : 0,
            ]
        ];

        if (Util::checkAppVersion('1.2.6') !== '小')
        {
            //0：未添加；1：已添加；2：审核中；3=>审核失败
            $statusTmp = 0;
            $placeholder = '暂无';
            $mediaData = [
                'title' => '音频/视频介绍',
                'placeholder' => $placeholder,
                'content' => '',
                'pic_list' => [],
                'status' => $statusTmp,
                'cover_img' => '',
                'type' => 0,
                'duration' => ''
            ];
            if (isset($checkInfo['media_intro']['status']))
            {
                switch ($checkInfo['media_intro']['status'])
                {
                    case 3:
                    case 0:
                        $statusTmp = 2;
                        $placeholder = '审核中';
                        break;
                    case 1:
                        $statusTmp = 1;
                        $placeholder = '已添加';
                        break;
                    case 2:
                        $statusTmp = 3;
                        $placeholder = '审核失败';
                        break;
                }
                if ($checkInfo['media_intro']['status'] === 1)
                {
                    $mediaData = [
                        'title' => '音频/视频介绍',
                        'placeholder' => $placeholder,
                        'content' => $extend['media_intro']['url'],
                        'pic_list' => [],
                        'status' => 1,
                        'cover_img' => $extend['media_intro']['img'],
                        'type' => (int)$extend['media_intro']['type'],
                        'duration' => $extend['media_intro']['duration']
                    ];
                } else
                {
                    $mediaData = [
                        'title' => '音频/视频介绍',
                        'placeholder' => $placeholder,
                        'content' => $checkInfo['media_intro']['url'],
                        'pic_list' => [],
                        'status' => $statusTmp,
                        'cover_img' => $checkInfo['media_intro']['img'],
                        'type' => (int)$checkInfo['media_intro']['type'],
                        'duration' => $checkInfo['media_intro']['duration']
                    ];
                }
            }
            //status 0=>待审核 1=>审核通过 2=>审核不通过 3=>审核终止（咨询师新增审核记录）',
            $resData[] = $mediaData;
        }
        return show(config('code.success'), '请求成功', $resData);

    }

    /**
     * 修改个人信息
     * @return Json|void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function modifyInfo()
    {
        $type = input('type/d', 0);
        $data = [
            'extend' => $this->astrInfo['extend']
        ];
        $oss = Env::get('host.photo');
        // 是否 已经 完善完资料
        $isCompleteInformation = isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0;
        $updateAstr = false;
        switch ($type)
        {
            case 1://头像
                $avatar = input('avatar/s', 0);
                if (!$avatar)
                {
                    return show(config('code.error'), '请上传头像');
                }
                if (strpos($avatar, $oss) === false)
                {
                    $avatarTmp = $oss . $avatar;
                } else
                {
                    $avatarTmp = $avatar;
                }
                $aliRes = AliyunFilterWord::checkImg(1, $avatarTmp, 'voice_mic');
                if ($aliRes['status'] === false)
                {
                    return show(config('code.error'), '头像包含' . $aliRes['text']);
                }
                if ($isCompleteInformation)
                {   // 完善 资料 后   更新信息  需要审核
                    $checkExtend['avatar'] = $avatar;
                } else
                {   // 未完善 资料  更新信息  不审核
                    $data['avatar'] = $avatar;
                    $updateAstr = true;
                }
                break;
            case 2://昵称
                $name = input('name/s', '');
                if (!$name)
                {
                    return show(config('code.error'), '请输入名称');
                }
                if (mb_strlen($name) > 10)
                {
                    return show(config('code.error'), '昵称最多10字');
                }
                $aliRes = AliyunFilterWord::checkText($name, 'article_comment');
                if ($aliRes)
                {
                    return show(config('code.error'), '昵称包含' . $aliRes['label']);
                }
                $num = (new ZlcrAstr())->where('nickname', $name)->count('id');
                if ($num)
                {
                    return show(config('code.error'), '当前名称已被注册,请更换名称');
                }
                if ($isCompleteInformation)
                {   // 完善 资料 后   更新信息  需要审核
                    $checkExtend['nickname'] = $name;
                } else
                {   // 未完善 资料  更新信息  不审核
                    $data['nickname'] = $name;
                    $updateAstr = true;
                }
                break;
            case 3://简介
                $content = input('intro/s', '');
                $picList = input('pic_list/a', '');
                $aliRes = AliyunFilterWord::checkText($content, 'article_comment');
                if ($aliRes)
                {
                    return show(config('code.error'), '资历信息包含' . $aliRes['label']);
                }
                foreach ($picList as $value)
                {
                    if (strpos($value, $oss) === false)
                    {
                        $value = $oss . $value;
                    }
                    $aliRes = AliyunFilterWord::checkImg(1, $value, 'voice_mic');
                    if ($aliRes['status'] === false)
                    {
                        return show(config('code.error'), '资历图片包含' . $aliRes['text']);
                    }
                }
                if ($isCompleteInformation)
                {   // 完善 资料 后   更新信息  需要审核
                    $checkExtend['qualification'] = [
                        'content' => $content,
                        'pic_list' => $picList
                    ];
                } else
                {   // 未完善 资料  更新信息  不审核
                    $data['extend']['qualification'] = [
                        'content' => $content,
                        'pic_list' => $picList
                    ];
                    $data['extend']['complete_information_data'][3] = 1;
                    $updateAstr = true;
                }
                break;
            case 4://营业介绍
                $intro = input('work_intro/s', '');
                if (mb_strlen($intro) > 60)
                {
                    return show(config('code.error'), '营业介绍最多60字');
                }
                $aliRes = AliyunFilterWord::checkText($intro);
                if ($aliRes)
                {
                    return show(config('code.error'), '营业介绍包含' . $aliRes['label']);
                }
                if ($isCompleteInformation)
                {
                    $checkExtend['work_intro'] = $intro;
                } else
                {
                    $data['extend']['work_intro'] = $intro;
                    $data['extend']['complete_information_data'][4] = 1;
                    $updateAstr = true;
                }
                break;
            case 5://服务时间
                $serviceTimes = input('service_time/s', '');
                $aliRes = AliyunFilterWord::checkText($serviceTimes);
                if ($aliRes)
                {
                    return show(config('code.error'), '服务时间包含' . $aliRes['label']);
                }
                if ($isCompleteInformation)
                {
                    $checkExtend['service_time'] = $serviceTimes;
                } else
                {
                    $data['extend']['service_time'] = $serviceTimes;
                    $data['extend']['complete_information_data'][5] = 1;
                    $updateAstr = true;
                }
                break;
            case 6://绑定准了号
                $uen = input('uen/s', '');
                //判断绑定的准了号，是否与该账户的手机号一样，如果不一样，那么提示
                $userApp = (new \app\common\model\User())->field('id,tel')->where('uen', $uen)->find();
                if (!$userApp)
                {
                    return show(0, '绑定失败，该准了号不存在！');
                }
                if ($this->astrInfo['tel'] !== $userApp['tel'])
                {
                    return show(0, '绑定失败，该准了号绑定的手机号，与您当前的手机号不一致！');
                }
                $res = (new ZlcrAstr())->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], ['uid' => $userApp['id']]);
                if ($res === false)
                {
                    return show(config('code.error'), '准了号绑定失败！');
                }
                return show(config('code.success'), '准了号绑定成功！');
            case 7://视频/音频介绍
                $introType = input('intro_type/d', 0);//1=>音频 2=>视频
                $coverImg = input('cover_img/s', '');
                $url = input('url/s', '');//视频封面图
                $duration = input('duration/s', '');//音频时长
                if (!$url)
                {
                    return show(config('code.error'), '视频/音频介绍地址不能为空');
                }
                if (!in_array($introType, [1, 2], true))
                {
                    return show(config('code.error'), '请求异常');
                }
                if ($introType === 1 && !$duration)
                {
                    return show(config('code.error'), '音频时长不能为空');
                }
                if ($introType === 2 && !$coverImg)
                {
                    return show(config('code.error'), '视频封面图不能为空');
                }
                $checkExtend['media_intro'] = [
                    'type' => $introType,
                    'img' => $coverImg,
                    'url' => $url,
                    'duration' => $duration
                ];
                break;
        }
        if ($isCompleteInformation === 0 && isset($data['extend']['complete_information_data'][3], $data['extend']['complete_information_data'][4], $data['extend']['complete_information_data'][5]))
        {
            unset($data['extend']['complete_information_data']);
            $data['extend']['is_complete_information'] = 1;
            //如果已经完善资料,且是邀请入住的直接修改状态为认证完成
            if ((int)$this->astrInfo['check_status'] !== 40)
            {
                $isInvite = (new Zlcr3ConsultAuthCode())->getAstrCodeStatus($this->astrInfo['id']);
                if ($isInvite)
                {
                    $updateData['check_status'] = 40;
                    $updateData['astr_level'] = 0;
                    $updateData['astro2_level'] = 0;
                    $updateData['dice_level'] = 0;
                    $updateData['tarot_level'] = 0;
                    $authStatus['custom_report'] = 0;
                    $authStatus['question_answer_astr'] = 0;
                    $authStatus['question_answer_dice'] = 0;
                    $authStatus['question_answer_tarot'] = 0;
                    $updateData['auth_status'] = json_encode($authStatus, JSON_UNESCAPED_UNICODE);
                    (new ZlcrAstr())->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], $updateData);
                }
            }
        }
        if ($updateAstr === true)
        {
            $data['extend'] = isset($data['extend']) ? json_encode($data['extend'], JSON_UNESCAPED_UNICODE) : '';
            (new ZlcrAstr())->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], $data);
        }
        if (isset($checkExtend))
        {
            $checkModel = new Zlcr3AstrModifyCheck();
            $newCheckId = $checkModel->where(['astr_id' => $this->astrInfo['id'], 'type' => $type, 'status' => 0])->order('id', 'DESC')->field('id')->find();
            if ($newCheckId)
            {
                $checkModel->where('id', $newCheckId['id'])->update(['status' => 3, 'update_time' => time()]);
            }

            $checkModel->insert([
                'status' => 0,
                'astr_id' => $this->astrInfo['id'],
                'type' => $type,
                'extend' => json_encode($checkExtend, true),
                'create_time' => time()
            ]);
        }
        return show(config('code.success'), '修改成功');
    }

    /**
     * 获取营业介绍
     * @return Json
     */
    public function getWorkIntro()
    {
        $extend = $this->astrInfo['extend'];
        return show(config('code.success'), '', [
            'content' => $extend['work_intro'] ?? ''
        ]);
    }

    /**
     * 修改营业状态
     * @return Json
     */
    public function alterWorkStatus()
    {
        $data = [
            'extend' => $this->astrInfo['extend']
        ];
        $intro = input('content/s', '');
        $status = input('status/d', 0);
        if (!in_array($status, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if ($status === 1)
        {
            $complete = isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0;
            if ($complete === 0)
            {
                return show(config('code.error'), '请先完善资料');
            }
            if (!$this->astrInfo['tel'])
            {
                return show(config('code.error'), '请绑定手机号');
            }
            if (!$this->astrInfo['uid'])
            {
                return show(config('code.error'), '请绑定准了号');
            }
            if (empty($intro))
            {
                return show(config('code.error'), '请输入营业介绍～');
            }
            if (mb_strlen($intro) > 40)
            {
                return show(config('code.error'), '营业介绍最多40字');
            }
        }
        //开启营业
        (new Zlcr3ConsultAccount())->updateData($this->astrInfo['id'], ['status' => $status]);
        if ($status === 1)
        {
            $data['extend']['work_intro'] = $intro;
            $data['extend'] = isset($data['extend']) ? json_encode($data['extend'], JSON_UNESCAPED_UNICODE) : '';
            (new ZlcrAstr())->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], $data);
        }
        return show(config('code.success'), '修改成功');
    }

    /**
     * 用户完善资料
     * @return Json
     * @throws Exception
     */
    public function compoleteInfo()
    {
        $data['userinfo'] = $param = $this->request->param();

        //todo 校验信息
//back: "/upload/check/right/20210311/9a2fe81e71ea00fde00a83a6cc6086be.jpg"
//bank_branch_code: "308100005078"
//bank_name: "招商银行"
//bank_num: "6214850115717628"
//bank_user_id_number: "130984199009063611"
//bank_username: "李柏楠"
//bank_verfiy: "842750"
//face: "/upload/check/left/20210311/ee0d85fda4aff46408e8c311df330ae0.jpg"
//holding: "/upload/check/pic/20210311/a8f39e44c2b8717f3bb8845e10c71419.jpg"
//id_number: "130984199009063611"
//nickname: "李老师"
//tel: "18502127689"
//truename: "李柏楠"
        $oss = Env::get('host.photo');

        //astro认证状态 10=>占星师考核  11=>待审核  12=>考核未通过 20=>资料填写 21=>资料待审核 22=>资料审核未通过 30=>培训   40=>认证完成（可接单）
        $zlAstrModel = new ZlcrAstr();
        $zlAstrInfoModel = new ZlcrAstrInfo();
        $astrInfo = $zlAstrInfoModel->getInfoById($this->astrInfo['id']);
        if ($this->request->isPost())
        {
            //新增占星师身份信息
            $paramRes = $this->checkCompoleteInfoParam($param, $zlAstrModel);
            if ($paramRes['status'] === false)
            {
                return show(0, $paramRes['msg'], $paramRes['data']);
            }
            //支行名称替换
            if ($param['bank_name'] === '上海浦东发展银行')
            {
                $param['bank_name'] = '浦发银行';
            }
            //获取占星师身份信息是否存在，存在则更新
            $astrInfoData = [
                'astr_id' => $this->astrInfo['id'],
                'name' => $param['truename'],
                'telphone' => $this->astrInfo['tel'],
                'id_card' => $param['id_number'],
                'left_pic' => $param['face'],
                'left_pic_info' => '',
                'right_pic' => $param['back'],
                'right_pic_info' => '',
                'hand_idcard_pic' => $param['holding'],
                'hand_idcard_pic_info' => '',
                'bank_card' => $param['bank_num'],
                'bank_name' => $param['bank_name'],
                'bank_id_card' => $param['bank_user_id_number'],
                'bank_id_card_name' => $param['bank_username'],
                'bank_info' => '',
                'bank_branch_info' => '',
                'create_time' => time()
            ];

            $uInfo2 = (new \app\common\cachemodel\User())->uenSearch(0, $param['uen'], 'id');

            $astrData = [
                'avatar' => $param['avatar'],
                'nickname' => $param['nickname'],
                'uid' => (int)$uInfo2['id'],
                'extend' => $this->astrInfo['extend']
            ];
            $astrData['extend']['work_intro'] = $param['work_intro'];
            $astrData['extend']['service_time'] = $param['service_time'];
            $astrData['extend']['qualification'] = [
                'content' => $param['intro'],
                'pic_list' => $param['pic_list']
            ];
            $aliRes = AliyunFilterWord::checkText($param['nickname'], '');
            $aliMsg = '昵称';
            if (!$aliRes)
            {
                $aliRes = AliyunFilterWord::checkText($param['work_intro'], '');
                $aliMsg = '营业介绍';
            }
            if (!$aliRes)
            {
                $aliRes = AliyunFilterWord::checkText($param['service_time'], '');
                $aliMsg = '服务时间';
            }
            if (!$aliRes)
            {
                $aliRes = AliyunFilterWord::checkText($param['intro'], '');
                $aliMsg = '资历信息';
            }
            if (!$aliRes)
            {
                $aliRes = AliyunFilterWord::checkImg(1, $oss . $param['avatar'], 'voice_mic');
                $aliMsg = '头像';
                if ($aliRes['status'] === false)
                {
                    $aliRes['label'] = $aliRes['text'];
                } else
                {
                    $aliRes = [];
                }
            }
            if (!$aliRes)
            {
                $aliMsg = '资历图片';
                foreach ($param['pic_list'] as $value)
                {
                    $aliRes = AliyunFilterWord::checkImg(1, $oss . $value, 'voice_mic');
                    if ($aliRes['status'] === false)
                    {
                        $aliRes['label'] = $aliRes['text'];
                        break;
                    }
                    $aliRes = [];
                }
            }
            if ($aliRes)
            {
                return show(config('code.error'), $aliMsg . '含有' . $aliRes['label']);
            }

            //识别身份证信息
            //验证身份证正面照片
            $res = $this->checkPicOfIdCard($this->astrInfo['id'], 3, $astrInfoData['left_pic']);
            if ($res['status'] === true)
            {//验证成功
                $astrInfoData['name'] = $res['data']['name'];//真实姓名
                $astrInfoData['id_card'] = $res['data']['idcard'];//身份证号
                $astrInfoData['left_pic_info'] = json_encode($res['data']);//身份证正面图片信息
            } else
            {
                return show(0, '新增失败，身份证正面照片验证失败！');
            }

            //验证身份证反面照片
            $res = $this->checkPicOfIdCard($this->astrInfo['id'], 4, $astrInfoData['right_pic']);
            if (!$res['status'])
            {
                return show(0, '新增失败，身份证反面照片验证失败！');
            } else
            {
                $astrInfoData['right_pic_info'] = json_encode($res['data']);//身份证反面图片信息
            }

            //验证手持身份证照片
            $res = $this->checkPicOfIdCard($this->astrInfo['id'], 5, $astrInfoData['hand_idcard_pic']);
            if (!$res['status'])
            {
                return show(0, '新增失败，手持身份证照片验证失败！');
            } else
            {
                if ($res['data']['score'] < 0.3)
                {
                    Log::write('新增手持身份证照片认证结果，小于0.3（需要降低点）', 'error', true);
                    return show(0, '新增失败，手持身份证照片认证失败！');
                } else
                {
                    $astrInfoData['hand_idcard_pic_info'] = json_encode($res['data']);//手持身份证正面图片信息
                }
            }

            //验证银行卡信息
            $bankCheckRes = Util::checkBankIdentityThreeElements($astrInfoData['bank_card'], $astrInfoData['bank_id_card'], $astrInfoData['bank_id_card_name']);
            if ($bankCheckRes['status'] === false)
            {
                $data['compeleteState'] = 3;
                $data['compeleteText'] = "<span class='tip'>{$bankCheckRes['msg']}</span>，请修改后重新提交审核。";
                return show(0, $bankCheckRes['msg'] . '，请修改后重新提交审核。');
            } else
            {
                $astrInfoData['bank_info'] = json_encode($bankCheckRes['data']);

                //验证开户行是否正确
                if (strpos($bankCheckRes['data']['bankName'], $astrInfoData['bank_name']) === false && strpos($astrInfoData['bank_name'], $bankCheckRes['data']['bankName']) === false)
                {//不包含 解析出来有可能是 中国工商银行
                    //---------------------------------------------------------------
                    //[ 2024-07-31T14:18:17+08:00 ] 175.167.148.196 POST wechat.goddessxzns.com/astrologer/v2/user/compoleteInfo
                    //[ error ] 请求头：{"model":"taro  RMX3700","channel":"astrologer","version":"1.2.2","access-token":"b995d98a4beba4855222bb94089eeb1b86561185||116444","user-agent":"Dart\/3.2 (dart:io)"}用户新增银行卡资料，支持的银行卡错误（需要更新占星师前端的银行卡列表 或者 去掉银行名字的验证）：用户选择的银行=中国农业银行，查询云市场的支行名字为：农业银行
                    //---------------------------------------------------------------
                    Log::write('用户新增银行卡资料，支持的银行卡错误（需要更新占星师前端的银行卡列表 或者 去掉银行名字的验证）：用户选择的银行=' . $astrInfoData['bank_name'] . '，查询云市场的支行名字为：' . $bankCheckRes['data']['bankName'], 'error', true);
                    return show(0, $bankCheckRes['msg'] . '，开户行错误，请修改后重新提交审核。');
                }

                //根据联行号查询支行信息
                $bank_branch_info = Util::checkBankCode($param['bank_branch_code']);
                if ($bank_branch_info['status'])
                {//成功，检查开户行是否一样
//                    if (strpos($bank_branch_info['data']['bank'], $bank_name) === false)
//                    {//不包含 解析出来有可能是 中国工商银行
//                        Log::write('用户编辑银行卡资料，支持的银行卡错误（需要更新占星师前端的银行卡列表 或者 去掉银行名字的验证）：用户选择的银行=' . $bank_name . '，查询云市场的支行名字为：' . $bank_branch_info['data']['bank'], 'error', true);
//                        return show(0, $bankCheckRes['msg'] . '，开户行错误，请修改后重新提交审核。');
//                    }
                    $astrInfoData['bank_name'] = $bank_branch_info['data']['bank'];
                    $astrInfoData['bank_branch_name'] = $bank_branch_info['data']['lName'];
                    $astrInfoData['bank_branch_info'] = json_encode($bank_branch_info['data']);
                } else
                {//失败
                    Log::write('支行信息查询失败，请修改后重新提交审核。', 'error', true);
                    return show(0, $bankCheckRes['msg'] . '支行信息查询失败，请修改后重新提交审核。');
                }


                //查询支行信息，这里不做强验证支行信息查询失败，需要客服联系用户获取（防止用户不知道支行信息，走不下去流程）
//                $bank_branch_info = Util::checkBankBranchInfo($astrInfoData['bank_card']);
//                if ($bank_branch_info['status'])
//                {//成功，检查开户行是否一样
//                    if (strpos($bank_branch_info['data']['bank'], $astrInfoData['bank_name']) === false)
//                    {//不包含 解析出来有可能是 中国工商银行
//                        Log::write('用户新增资料，支持的银行卡错误（需要更新占星师前端的银行卡列表 或者 去掉银行名字的验证）：用户选择的银行=' . $astrInfoData['bank_name'] . '，查询云市场的支行名字为：' . $bank_branch_info['data']['bank'], 'error', true);
//                        return show(0, '开户行错误，请修改后重新提交审核。');
//                    } else
//                    {//包含
//                        $astrInfoData['bank_name'] = $bank_branch_info['data']['bank'];
//                        $astrInfoData['bank_branch_name'] = $bank_branch_info['data']['addr'];
//                        $astrInfoData['bank_branch_info'] = json_encode($bank_branch_info['data']);
//                    }
//                } else
//                {//失败，todo 发送钉钉通知
//                    Log::write('新增-查询支行信息，这里不做强验证支行信息查询失败，需要客服联系用户获取（防止用户不知道支行信息，走不下去流程）', 'error', true);
//                }
            }

            //添加数据
            $res1 = $zlAstrInfoModel->SaveData($astrInfoData);
            if (!$res1)
            {
                $data['compeleteState'] = 4;
                $data['compeleteText'] = "<span class='tip'>服务异常，请稍后重试！</span>";
                Log::write('保存资料失败1,msg=', json_encode($res1), 'error', true);
                return show(0, '服务异常，请稍后重试！', $data);
            }
            $res2 = $zlAstrModel->UpdateData($this->astrInfo['id'], ['id' => $this->astrInfo['id']], [
                'check_status' => 30,
                'uid' => $astrData['uid'],
                'nickname' => $astrData['nickname'],
                'avatar' => $astrData['avatar'],
                'extend' => $astrData['extend']
            ]);
            if (!$res2)
            {
                $data['compeleteState'] = 4;
                $data['compeleteText'] = "<span class='tip'>服务异常，请稍后重试！</span>";
                Log::write('保存资料失败2,msg=', 'error', true);
                return show(0, '服务异常，请稍后重试！', $data);
            }
            $data['compeleteState'] = 5;
            $data['compeleteText'] = "提交成功";
            $data['userinfo'] = null;
            return show(200, '提交成功', $data);
        } else
        {
            if ($astrInfo)
            {
                $data['userinfo'] = [
                    'avatar' => $this->astrInfo['avatar'],
                    'nickname' => $this->astrInfo['nickname'],
                    'truename' => Util::decryptWithOpenssl($astrInfo['name']),
                    'id_number' => Util::decryptWithOpenssl($astrInfo['id_card']),
                    'face_private_url' => Upload::getOssPrivateUrl($astrInfo['left_pic']),
                    'back_private_url' => Upload::getOssPrivateUrl($astrInfo['right_pic']),
                    'holding_private_url' => Upload::getOssPrivateUrl($astrInfo['hand_idcard_pic']),
                    'face' => $astrInfo['left_pic'],
                    'back' => $astrInfo['right_pic'],
                    'holding' => $astrInfo['hand_idcard_pic'],
                    'bank_num' => Util::decryptWithOpenssl($astrInfo['bank_card']),
                    'bank_name' => Util::decryptWithOpenssl($astrInfo['bank_name']),
                    'bank_address' => Util::decryptWithOpenssl($astrInfo['bank_branch_name']),
                    'bank_branch_code' => json_decode(Util::decryptWithOpenssl($astrInfo['bank_branch_info']), true)['bankCode'],
                    'bank_username' => Util::decryptWithOpenssl($astrInfo['name']),
                    'bank_user_id_number' => Util::decryptWithOpenssl($astrInfo['id_card']),
                    'bank_verfiy' => '',
                    'tel' => $this->astrInfo['tel'],
                ];
                if ($this->astrInfo['check_status'] == 22)
                {
                    //获取审核信息
                    $check = (new ZlcrContentCheck())->getContentCheckInfo($this->astrInfo['id'], 4, ['status', 'ali_ckeck', 'desc']);
                    $msg = $check['desc'] ?: $check['ali_ckeck'];
//                    $msg = '123';
                    $data['compeleteState'] = 4;
                    //获取私有图片地址
                    $data['userinfo']['face_private_url'] = Upload::getOssPrivateUrl($data['userinfo']['face']);
                    $data['userinfo']['back_private_url'] = Upload::getOssPrivateUrl($data['userinfo']['back']);
                    $data['userinfo']['holding_private_url'] = Upload::getOssPrivateUrl($data['userinfo']['holding']);
                    $data['compeleteText'] = $msg;
                    return show(200, $msg, $data);
                } elseif ($this->astrInfo['check_status'] == 21)
                {
                    $data['compeleteState'] = 3;
                    $data['compeleteText'] = "请等待客服审核，留意短信通知，1-3个工作日内完成审核。";
                    $data['userinfo'] = null;
                    return show(200, '请求成功', $data);
                } elseif ($this->astrInfo['check_status'] == 30)
                {
                    $data['compeleteState'] = 5;
                    $data['compeleteText'] = '恭喜您成功完善了相关资料';
                    $data['userinfo'] = null;
                    return show(200, '请求成功', $data);
                } else
                {
                    $data['compeleteState'] = 1;
//                    $data['compeleteState'] = 2; //test
                    $data['compeleteText'] = '请完善相关资料';
                    return show(200, '请求成功', $data);
                }
            } else
            {//没有信息，刚开始上传，只把手机号给用户返回
                $data['userinfo'] = [
                    'tel' => $this->astrInfo['tel'],
                ];
                $data['compeleteState'] = 1;
//                $data['compeleteState'] = 2;//test
                return show(200, '请求成功', $data);
            }
            return show(0, $msg ?? '', $data);
        }
    }

    /**
     * 验证用户完善资料请求参数
     * @param $param
     * @param $zlAstrModel
     * @return array
     */
    private function checkCompoleteInfoParam($param, $zlAstrModel)
    {
        $data['userinfo'] = $param;
//        if (!isset($param['avatar']) || !$param['avatar'])
//        {
//            return [
//                'status' => false,
//                'msg' => '请上传头像',
//                'data' => []
//            ];
//        }

//        if (!isset($param['nickname']) || !$param['nickname'])
//        {
//            return [
//                'status' => false,
//                'msg' => '请填写昵称',
//                'data' => []
//            ];
//        }

        if (!isset($param['truename']) || !$param['truename'])
        {
            return [
                'status' => false,
                'msg' => '请输入真实姓名',
                'data' => []
            ];
        }

        if (!isset($param['id_number']) || !$param['id_number'])
        {
            return [
                'status' => false,
                'msg' => '请输入身份证号',
                'data' => []
            ];
        }

        if (!isset($param['face']) || !$param['face'])
        {
            return [
                'status' => false,
                'msg' => '请上传身份证正面照片',
                'data' => []
            ];
        }

        if (!isset($param['back']) || !$param['back'])
        {
            return [
                'status' => false,
                'msg' => '请上传身份证反面照片',
                'data' => []
            ];
        }

        if (!isset($param['holding']) || !$param['holding'])
        {
            return [
                'status' => false,
                'msg' => '请上传手持身份证照片',
                'data' => []
            ];
        }

        if (!isset($param['bank_num']) || !$param['bank_num'])
        {
            return [
                'status' => false,
                'msg' => '请输入银行卡号',
                'data' => []
            ];
        }

        if (!isset($param['bank_name']) || !$param['bank_name'])
        {
            return [
                'status' => false,
                'msg' => '请输入开户行',
                'data' => []
            ];
        }

//        if (!isset($param['bank_address']) || !$param['bank_address'])
//        {
//            return [
//                'status' => false,
//                'msg' => '请输入支行信息',
//                'data' => []
//            ];
//        }

        if (!isset($param['bank_username']) || !$param['bank_username'])
        {
            return [
                'status' => false,
                'msg' => '请输入收款人姓名',
                'data' => []
            ];
        }

        if (!isset($param['bank_user_id_number']) || !$param['bank_user_id_number'])
        {
            return [
                'status' => false,
                'msg' => '请输入收款人身份证号',
                'data' => []
            ];
        }

        if (!isset($param['bank_verfiy']) || !$param['bank_verfiy'])
        {
            return [
                'status' => false,
                'msg' => '请输入验证码',
                'data' => []
            ];
        }

        //验证手机验证码
        $code = Cache::get($this->astrInfo['tel']);
        if ($code != $param['bank_verfiy'])
        {
            $data['compeleteState'] = 4;
            $data['compeleteText'] = '您填写的 <span class="tip">验证码错误</span> 错误，请修改后重新提交审核。';
            return [
                'status' => false,
                'msg' => '验证码错误',
                'data' => $data
            ];
        }

        //昵称不能重复
//        $aid = $zlAstrModel->where(['nickname' => $param['nickname']])->column('id');
//        if ($aid && (int)$aid[0] !== (int)$this->astrInfo['id'])
//        {
//            $data['compeleteState'] = 4;
//            $data['compeleteText'] = '您填写的 <span class="tip">昵称</span> 已被注册，请修改后重新提交审核。';
//            return [
//                'status' => false,
//                'msg' => '当前昵称已被注册，请重新输入！',
//                'data' => $data
//            ];
//        }

        //姓名身份证信息验证
//        $resData = Util::checkIdentityTwoElements($param['truename'], $param['id_number']);
//        if ($resData['status'] === false)
//        {
//            $data['compeleteState'] = 4;
//            $data['compeleteText'] = '您填写的 <span class="tip">身份证号</span> 信息不符合要求，请修改后重新提交审核。';
//            return [
//                'status' => false,
//                'msg' => '身份信息错误',
//                'data' => $data
//            ];
//        }

        //验证银行卡信息
//        $bankCheckRes = Util::checkBankIdentityThreeElements($param['bank_num'], $param['bank_user_id_number'], $param['bank_username']);
//        //todo 是否需要验证开户行
//        if ($bankCheckRes['status'] === false)
//        {
//            $data['compeleteState'] = 3;
//            $data['compeleteText'] = "<span class='tip'>{$bankCheckRes['msg']}</span>，请修改后重新提交审核。";
//            return [
//                'status' => false,
//                'msg' => $bankCheckRes['msg'] . '，请修改后重新提交审核。',
//                'data' => $data
//            ];
//        }
//        return [
//            'status' => true,
//            'msg' => '',
//            'data' => []
//        ];
    }

    /**
     * 检查图片是否解析完成
     * @param int $astrId
     * @param int $type 3：身份证正面；4：身份证反面；5：手持身份证；
     * @param string $img_url 图片的oss地址
     * @return array|false[]
     */
    private function checkPicOfIdCard(int $astrId, int $type = 3, string $img_url = '')
    {
        $data = [
            'status' => false,
            'data' => ''
        ];

        $key = [
            3 => 'left_pic',
            4 => 'right_pic',
            5 => 'hand_idcard_pic',
        ];

        $uploadPath = Cache::get('astr_admin:upload_path:' . $astrId, []);

        if (isset($uploadPath[$key[$type]]['path'], $uploadPath[$key[$type]]['data']) && $img_url === $uploadPath[$key[$type]]['path'])
        {
            return [
                'status' => true,
                'data' => $uploadPath[$key[$type]]['data']
            ];
        } else
        {
            return $data;
        }
    }

    /**
     * 获取咨询师等级信息
     * 注意：用于能力分记录页面，有连线咨询资格的时候，那么展示“连线单价”tab，没有 则不显示 “连线单价” tab；
     */
    public function getUserLevelInfo()
    {
        $apiHost = Env::get('host.domain');
        $imgHost = Env::get('host.photo');
        $nowTime = time();
        $astrModel = new ZlcrAstr();

        $authStatus = $this->astrInfo['auth_status'];
        $data = [];
        $hint = '';//顶部提示

        if ($authStatus['custom_report'] === 1)
        {   // 定制报告
            $astrLevel = abs($this->astrInfo['astr_level']);
            $data[] = [
                'type' => 1,
                'title' => '定制报告能力分',
                'img' => $imgHost . '/mini/astrologer/test/1.png',
                'grade' => $this->astrInfo['astro_grade'],
                'level_name' => $astrModel->astrLevelName2[1][$astrLevel],
                'proportion' => ($astrModel->astrLevelProportion[$astrLevel] * 100) . '%',
                'protocol_url' => $apiHost . '/web/rule_astrologer',
            ];
        } else
        {
            $hint = '定制报告';
        }

        if ($authStatus['question_answer_astr'] === 1)
        {   // 问答星盘
            $astro2Level = abs($this->astrInfo['astro2_level']);
            $data[] = [
                'type' => 2,
                'title' => '问答-占星能力分',
                'img' => $imgHost . '/mini/astrologer/test/1.png',
                'grade' => $this->astrInfo['astro2_grade'],
                'level_name' => $astrModel->astrLevelName2[2][$astro2Level],
                'proportion' => ($astrModel->getAstrQuestionAnswerProportion($nowTime, 1, $astro2Level) * 100) . '%',
                'protocol_url' => $apiHost . '/web/rule_astro_grade',
            ];
        } else
        {
            if ($hint)
            {
                $hint .= '、';
            }
            $hint .= '问答星盘';
        }

        if ($authStatus['question_answer_tarot'] === 1)
        {   // 问答塔罗
            $tarotLevel = abs($this->astrInfo['tarot_level']);
            $data[] = [
                'type' => 4,
                'title' => '问答-塔罗能力分',
                'img' => $imgHost . '/mini/astrologer/test/1.png',
                'grade' => $this->astrInfo['tarot_grade'],
                'level_name' => $astrModel->astrLevelName2[4][$tarotLevel],
                'proportion' => ($astrModel->getAstrQuestionAnswerProportion($nowTime, 3, $tarotLevel) * 100) . '%',
                'protocol_url' => $apiHost . '/web/rule_tarot_grade',
            ];
        } else
        {
            if ($hint)
            {
                $hint .= '、';
            }
            $hint .= '问答塔罗';
        }

        if ($hint !== '')
        {
            $hint = '你没有通过' . $hint . '考试认证，暂时没有相关能力分，快去前往考试吧～';
        }

        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($this->astrInfo['id']);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        $res = [
            'list' => $data,
            'hint' => $hint,
            'is_consult' => $isConsult,//新增字段
        ];

        return show(200, '请求成功', $res);
    }

    /**
     * 我的-》能力分记录-》连线单价
     * @return Json
     * @throws \Exception
     */
    public function rtcPriceInfo()
    {
        $consultModel = new Zlcr3ConsultAccount();
        $consultInfo = $consultModel->getInfoById($this->astrInfo['id']);

        $price = (float)sprintf('%.2f', $consultInfo['price'] * $consultModel->getPercent($consultInfo['percent'], 1) / 10);

        return show(config('code.success'), 'success', [
            'list' => [
                [
                    'hint' => '尊敬的咨询师你好，很高兴与您合作，我们的等级系统暂未上线。但是您当前的所有服务行为将被我们记录，作为您之后的等级评估的依据，您的等级将影响你的收益和在平台曝光量以及各类特权。您作为准了精心挑选的咨询师，我们会根据你的服务质量和专业程度综合评估，为您制定服务单价，以下单价不代表您的最终服务价格，我们可能会根据实际情况进行合理调整，感谢您的信任。',
                    'title' => '当前服务单价',
                    'list' => [
                        [
                            'title' => '服务单价',
                            'des' => $price . '元/分钟'
                        ]
                    ],
                    'des' => [
                        '常规咨询分成：25%',
                        '同一用户咨询次数大于等于2次且小于等于5次：分成30%',
                        '同一用户咨询次数大于等于6次且小于等于10次：分成35%',
                        '同一用户咨询次数大于10次分成40%',
                    ]
                ],
            ]
        ]);
    }
}
